﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls.Primitives;

namespace Lib.WPF.Dependents;
/// <summary>
/// 
/// </summary>
public static class PopupBehavior {

    /// <summary>
    /// 
    /// </summary>
    public static readonly DependencyProperty IsOpenProperty = DependencyProperty.RegisterAttached("IsOpen", typeof(bool), typeof(PopupBehavior), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnIsOpenChanged));
    /// <summary>
    /// 
    /// </summary>
    public static bool GetIsOpen(DependencyObject obj) => (bool)obj.GetValue(IsOpenProperty);
    /// <summary>
    /// 
    /// </summary>
    public static void SetIsOpen(DependencyObject obj, bool value) => obj.SetValue(IsOpenProperty, value);
    /// <summary>
    /// 
    /// </summary>
    private static void OnIsOpenChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e) {
        if (obj is Popup That) {
            That.IsOpen = (bool)e.NewValue;
            That.Closed -= Popup_Closed;
            That.Closed += Popup_Closed;
        }
    }
    /// <summary>
    /// 
    /// </summary>
    private static void Popup_Closed(object Sender, EventArgs e) {
        if (Sender is Popup That) {
            SetIsOpen(That, false);
        }
    }
}
